package prototipo.server.logic.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import prototipo.server.logic.exception.ExceptionLogic;

public class Email implements EmailIF {

	private String email;

	public Email(String newEmail) throws ExceptionLogic {
		this();
		this.setEmail(newEmail);
	}

	public Email() {
	}

	/**
	 * @return the email
	 */
	public String getEmail() {
		return email;
	}

	/**
	 * @param email
	 *            the email to set
	 * @throws ExceptionLogic
	 */
	public void setEmail(String email) throws ExceptionLogic {
		if (validateEmail(email))
			this.email = email;
	}

	private boolean validateEmail(String email2) throws ExceptionLogic {
		if (email2 == null)
			throw new ExceptionLogic("Email vazio.", new Throwable(
					"Email String is null."));
		Pattern padrao = Pattern.compile(".+@.+\\.[a-z]+");
		Matcher pesquisa = padrao.matcher(email2);
		if (!pesquisa.matches())
			throw new ExceptionLogic("Email incorreto. Padrao: nome@dominio.",
					new Throwable("Incorrect Email pattern."));
		return true;
	}

	public String toString() {
		return this.email;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Object#hashCode()
	 */
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((email == null) ? 0 : email.hashCode());
		return result;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Object#equals(java.lang.Object)
	 */
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (!(obj instanceof Email))
			return false;
		Email other = (Email) obj;
		if (email == null) {
			if (other.email != null)
				return false;
		} else if (!email.equals(other.email))
			return false;
		return true;
	}

}
